/*
 * @Author: 张继伟
 * @Date: 2025-10-29 13:46:45
 * @Description: 
 */
import React, { Suspense } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { Spin } from 'antd';
import { RouteItem, flattenRoutes } from '../config/routes';

// 路由加载组件
const RouteLoading: React.FC = () => (
  <div style={{ padding: 50, textAlign: 'center' }}>
    <Spin size="large" />
  </div>
);

// 生成路由组件
export const generateRoutes = (routes: RouteItem[]): React.ReactElement => {
  const flattenedRoutes = flattenRoutes(routes);

  return (
    <Suspense fallback={<RouteLoading />}>
      <Routes>
        {flattenedRoutes.map(route => (
          <Route
            key={route.key}
            path={route.path}
            element={
              <Suspense fallback={<RouteLoading />}>
                {route.component && React.createElement(route.component)}
              </Suspense>
            }
          />
        ))}
        {/* 默认重定向 */}
        <Route path="/" element={<Navigate to="/dashboard" replace />} />
        {/* 404 页面 */}
        <Route path="*" element={<div>404 - 页面不存在</div>} />
      </Routes>
    </Suspense>
  );
};

// 生成菜单项
export const generateMenuItems = (routes: RouteItem[]): any[] => {
  return routes
    .filter(route => !route.hideInMenu)
    .map(route => {
      const menuItem: any = {
        key: route.path,
        label: route.label,
        icon: route.icon ? React.createElement(route.icon) : undefined,
      };

      if (route.children && route.children.some(child => !child.hideInMenu)) {
        menuItem.children = generateMenuItems(route.children);
      }

      return menuItem;
    });
};